<template>
    <div class="pvc">
        <el-row>
          <!-- 头部1，放namespace选择框, 刷新按钮 -->
            <el-col :span="24">
            <el-card class="deploy-head-card" shadow="never" :body-style="{padding:'10px'}">
              <el-row>
                <!-- namespace下拉选择框 -->
                <el-col :span=8>
                  <span style="font-size: 14px;">命名空间：</span>
                  <el-select
                      @change="npChange"
                      size="small"
                      v-model="namespaceValue"
                      filterable>
                    <el-option
                        v-for="(item, index) in namespaceList"
                        :key="index"
                        :label="item.metadata.name"
                        :value="item.metadata.name"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="16" style="text-align:right;">
                  <el-button size="small" icon="Refresh" plain @click="getPvcs()">刷新</el-button>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
            <!-- 头部2，创建按钮 及搜索框 -->
            <el-col :span="24">
                <el-card class="pvc-head-card" shadow="never" :body-style="{padding:'10px'}">
                    <!-- float属性，会将多个同级标签放在同一行 -->
                    <div style="float: left;margin-right:10px;">
                        <el-button  size="small" type="primary" icon="Edit" @click="createpvcDrawer = true">创建</el-button>
                    </div>
                    <div>
                        <el-input class="pvc-head-search" size="small" clearable placeholder="请输入" v-model='searchValue'></el-input>
                        <el-button size="small" type="primary" plain icon="Edit" @click="getPvcs()">搜索</el-button>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="24">
                <div>
                    <el-card class="pvc-body-card" shadow="never" :body-style="{padding:'5px'}">
                        <el-table
                        style="width:100%;font-size:12px;margin-bottom:10px;"
                        :data="pvcList"
                        v-loading="appLoading">
                            <el-table-column width="20"></el-table-column>

                            <el-table-column align=left label="PVC名">
                                <template v-slot="scope">
                                    <a class="pvc-body-pvcname">{{ scope.row.metadata.name }}</a>
                                </template>
                            </el-table-column>

                            <el-table-column align=center label="状态">
                                <template v-slot="scope">
                                    <span :class="[scope.row.status.phase === 'Bound' ? 'success-status' : 'error-status']">{{ scope.row.status.phase }}</span>
                                </template>
                            </el-table-column>

                            <el-table-column align=center prop="spec.accessModes[0]" label="访问模式"></el-table-column>

<!--                            <el-table-column align=center prop="scope.row.status.capacity.storage" label="容量"></el-table-column>-->
                          <el-table-column align="left" label="容量">
                            <template v-slot="scope">
                              <a class="pvc-body-pvcname" v-if="scope.row.status.capacity && scope.row.status.capacity.storage">
                                {{ scope.row.status.capacity.storage }}
                              </a>
                              <span v-else>-</span> <!-- Display a dash or any placeholder when storage does not exist -->
                            </template>
                          </el-table-column>


<!--                            <el-table-column align=center prop="spec.claimRef.name" label="PVC"></el-table-column>-->

                            <el-table-column align=center min-width="100" label="创建时间">
                                <template v-slot="scope">
                                    <el-tag type="info">{{ timeTrans(scope.row.metadata.creationTimestamp) }} </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column align=center label="操作" min-width="120">
                                <template v-slot="scope">
                                    <el-button size="small" style="border-radius:2px;" icon="Edit" type="primary" plain @click="getPvcDetail(scope)">YAML</el-button>
                                    <el-button size="small" style="border-radius:2px;" icon="Delete" type="danger" @click="handleConfirm(scope, '删除', delPvc)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-pagination
                        class="pvc-body-pagination"
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-sizes="pagesizeList"
                        :page-size="pagesize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :prev-click="getPvcs"
                        :total="pvcTotal">
                        </el-pagination>
                    </el-card>
                </div>
            </el-col>
        </el-row>
        <el-dialog title="YAML信息" v-model="yamlDialog" width="45%" top="5%">
            <codemirror
                :value="contentYaml"
                border
                :options="cmOptions"
                height="500"
                style="font-size:14px;"
                @change="onChange"
            ></codemirror>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="yamlDialog = false">取 消</el-button>
                    <el-button type="primary" @click="updatePvc()">更 新</el-button>
                </span>
            </template>
        </el-dialog>

      <!--      创建PVC-->
      <el-drawer
          v-model="createpvcDrawer"
          direction="rtl"
          :before-close="handleClose"
          title="创建PVC资源"
          size="50%">
        <template #default>
          <!-- flex布局,居中 -->
          <el-row type="flex" justify="center">
            <el-col :span="20">
              <!-- ref绑定控件后，js中才能用this.$ref获取该控件 -->
              <!-- rules 定义form表单校验规则 -->
              <el-form ref="createpvcData"  :model="createpvcData" label-width="200px">
                <!-- prop用于rules中的校验规则的key -->

                <el-form-item class="deploy-create-form" label="PVC名称" prop="piplname" >
                  <el-input v-model="createpvcData.pvc_name"></el-input>
                </el-form-item>

                <el-form-item class="deploy-create-form" label="命名空间" prop="namespace">
                  <el-select v-model="createpvcData.namespace" filterable placeholder="请选择">
                    <el-option
                        v-for="(item, index) in namespaceList"
                        :key="index"
                        :label="item.metadata.name"
                        :value="item.metadata.name">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item class="deploy-create-form" label="存储模式" prop="giturl" >
                  <el-select v-model="createpvcData.access_modes" filterable placeholder="请选择">
                    <el-option
                        v-for="(item, index) in access_modes"
                        :key="index"
                        :label="item"
                        :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item class="deploy-create-form" label="存储空间" prop="piplname" >
                  <el-input placeholder="500m/1G" v-model="createpvcData.storage"></el-input>
                </el-form-item>

                <el-form-item class="deploy-create-form" label="StorageClassName" prop="giturl" >
                  <el-select v-model="createpvcData.storage_class_name" filterable placeholder="请选择">
                    <el-option
                        v-for="(item, index) in storage_class_name"
                        :key="index"
                        :label="item.Name"
                        :value="item.Name">
                    </el-option>
                  </el-select>
                </el-form-item>

              </el-form>
            </el-col>
          </el-row>
        </template>
        <!-- 插槽，抽屉footer -->
        <template #footer>
          <!-- 点击后赋值false，隐藏抽屉 -->
          <el-button @click="createpvcDrawer=false">取消</el-button>
          <el-button type="primary" @click="submitForm('createpvcData')">创建并执行</el-button>

        </template>
      </el-drawer>
    </div>
</template>

<script>
import common from "../../common/Config";
import httpClient from '@/request';
import yaml2obj from 'js-yaml';
import json2yaml from 'json2yaml';
export default {
    data() {
        return {
            //编辑器配置
            cmOptions: common.cmOptions,
            contentYaml: '',
            //分页
            currentPage: 1,
            pagesize: 10,
            pagesizeList: [10, 20, 30],
            //
            searchValue: '',
            namespaceValue: 'default',
            namespaceList: [],
            namespaceListUrl: common.k8sNamespaceList,
            appLoading: false,
            pvcList: [],
            pvcTotal: 0,

          access_modes: ["ReadWriteOnce","ReadOnlyMany","ReadWriteMany","ReadWriteOncePod"],

          storage_class_name:[],
          storage_class: {
            url: common.k8sStorageClassesList,
            pvc_name:"",
            namespace:"",
            access_modes:"",
            storage:"",
            storage_class_name: "",
          },


            getPvcsData: {
                url: common.k8sPvcList,
                params: {
                    filter_name: '',
                    namespace: '',
                    page: '',
                    limit: '',
                }
            },
          //添加
          createpvcDrawer: false,
          createpvcData: {
            url: common.k8sPvcCreate,
            pvc_name:"test123",
            namespace:"redis2",
            access_modes:"ReadWriteOnce",
            storage:"1G",
            storage_class_name: "local-path",
          },

            //详情
            pvcDetail: {},
            getPvcDetailData: {
                url: common.k8sPvcDetail,
                params: {
                    pvc_name: '',
                    namespace: ''
                }
            },

            //yaml更新
            yamlDialog: false,
            updatePvcData: {
                url: common.k8sPvcUpdate,
                params: {
                    namespace: '',
                    content: ''
                }
            },
            //删除
            delPvcData: {
                url: common.k8sPvcDel,
                params: {
                    pvc_name: '',
                    namespace: '',
                }
            }
        }
    },
    methods: {
        transYaml(content) {
            return json2yaml.stringify(content)
        },
        transObj(content) {
            return yaml2obj.load(content)
        },
        onChange(val) {
            this.contentYaml = val
        },
        handleSizeChange(size) {
            this.pagesize = size;
            this.getPvcs()
        },
        handleCurrentChange(currentPage) {
            this.currentPage = currentPage;
            this.getPvcs()
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
            .then(() => {
                done();
            })
            .catch(() => {});
        },
        ellipsis(value) {
            return value.length>15?value.substring(0,15)+'...':value
        },
        timeTrans(timestamp) {
            let date = new Date(new Date(timestamp).getTime() + 8 * 3600 * 1000)
            date = date.toJSON();
            date = date.substring(0, 19).replace('T', ' ')
            return date 
        },
        specTrans(str) {
            if ( str.indexOf('Ki') == -1 ) {
                return str
            }
            let num = str.slice(0,-2) / 1024 / 1024
            return num.toFixed(0)
        },
      //读取namespace列表
      getNamespaces() {
        httpClient.get(this.namespaceListUrl)
            .then(res => {
              this.namespaceList = res.data.items
            })
            .catch(res => {
              this.$message.error({
                message: res.msg
              })
            })
      },
        getPvcs() {
            this.appLoading = true
            this.getPvcsData.params.filter_name = this.searchValue
            this.getPvcsData.params.namespace = this.namespaceValue
            this.getPvcsData.params.page = this.currentPage
            this.getPvcsData.params.limit = this.pagesize
            console.log(this.searchValue)
            httpClient.get(this.getPvcsData.url, {params: this.getPvcsData.params})
            .then(res => {
                this.pvcList = res.data.items
                this.pvcTotal = res.data.total
            })
            .catch(res => {
                this.$message.error({
                message: res.msg
                })
            })
            this.appLoading = false
        },
        getPvcDetail(e) {
            this.getPvcDetailData.params.pvc_name = e.row.metadata.name
            this.getPvcDetailData.params.namespace = this.namespaceValue
          console.log( this.getPvcDetailData)
            httpClient.get(this.getPvcDetailData.url, {params: this.getPvcDetailData.params})
            .then(res => {
                this.pvcDetail = res.data
                this.contentYaml = this.transYaml(this.pvcDetail)
                this.yamlDialog = true
            })
            .catch(res => {
                this.$message.error({
                message: res.msg
                })
            })
        },

      //创建
      createpvcFunc() {
        this.createpvcData.pvc_name
        this.createpvcData.namespace
        this.createpvcData.access_modes
        this.createpvcData.storage
        this.createpvcData.storage_class_name
        console.log(this.createpvcData)


        httpClient.post(this.createpvcData.url, this.createpvcData)
            .then(res => {
              this.$message.success({
                message: res.msg
              })
            })
            .catch(res => {
              this.$message.error({
                message: res.msg
              })
            })
            .finally(() => {
              this.createpvcDrawer = false
              console.log (this.createpvcData)
              this.getPvcs()
            })
      },

      //StorageClasses查询
      GetStorageClasses() {
          httpClient.get(this.storage_class.url, {params: this.storage_class.params})
              .then(res => {
                this.storage_class_name = res.data
                console.log(this.storage_class_name)
              })
              .catch(res => {
                this.$message.error({
                  message: res.msg
                })
              })
        },

      //提交表单，验证数据
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.createpvcFunc()
          } else {
            return false
          }
        })
      },


        updatePvc() {
            let content = JSON.stringify(this.transObj(this.contentYaml))
            this.updatePvcData.params.namespace = this.namespaceValue
            this.updatePvcData.params.content = content
            httpClient.put(this.updatePvcData.url, this.updatePvcData.params)
            .then(res => {
                this.$message.success({
                message: res.msg
                })
            })
            .catch(res => {
                this.$message.error({
                message: res.msg
                })
            })
            this.yamlDialog = false
        },
        delPvc(e) {
            this.delPvcData.params.pvc_name = e.row.metadata.name
            this.delPvcData.params.namespace = this.namespaceValue
            console.log(this.delPvcData)
            httpClient.delete(this.delPvcData.url, {data: this.delPvcData.params})
            .then(res => {
                this.$message.success({
                message: res.msg
                })
            })
            .catch(res => {
                this.$message.error({
                message: res.msg
                })
            })
            .finally(() => {
                this.getPvcs()
              console.log("触发删除1")
            })
        },

      npChange() {
        this.getPvcs()
        localStorage.setItem('namespace', this.namespaceValue)
      },

        handleConfirm(obj, operateName, fn) {
            this.confirmContent = '确认继续 ' + operateName + ' 操作吗？'
            this.$confirm(this.confirmContent,'提示',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            })
            .then(() => {
                fn(obj)
                })
            .catch(() => {
                this.$message.info({
                    message: '已取消操作'
                })          
            })
            .finally(() => {
              console.log("触发删除2")
                this.getPvcs()
            })
        },
    },
  watch: {
    namespaceValue: function(newVal, oldVal) {
      console.log({newVal, oldVal});
      this.getPvcs()
    }
  },
  mounted() {
    if (localStorage.getItem('namespace')) {
      this.namespaceValue = localStorage.getItem('namespace')
    }
      this.getNamespaces()
      this.getPvcs()
      this.GetStorageClasses()
    }
}
</script>


<style scoped>
    .pvc-head-card,.pvc-body-card {
        border-radius: 1px;
        margin-bottom: 5px;
    }
    .pvc-head-search {
        width:160px;
        margin-right:10px; 
    }
    .pvc-body-pvcname {
        color: #4795EE;
    }
    .pvc-body-pvcname:hover {
        color: rgb(84, 138, 238);
        cursor: pointer;
        font-weight: bold;
    }
    .success-status {
        color: rgb(27, 202, 21);
    }
    .warning-status {
        color: rgb(233, 200, 16);
    }
    .error-status {
        color: rgb(226, 23, 23);
    }
</style>